package com.ficus.road.maintain.websocket;

import com.ficus.road.maintain.config.WebSocketConfig;
import com.ficus.road.maintain.core.exception.UnAuthorizedException;
import com.ficus.road.maintain.core.model.ReplayVideoRequestDTO;
import com.ficus.road.maintain.util.MobileChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@ServerEndpoint(value = "/ws/{carId}/{timestamp}", configurator = WebSocketConfig.class)
@Service
@Slf4j
@ConditionalOnProperty(prefix = "zhonghai", name = "enable_replay", havingValue = "true")
public class WebSocketV2Manager extends BaseWebSocketManager {

    public static volatile DateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    /**
     * 建立连接
     * 连接成功后，服务器的回调函数
     *
     * @param session session
     */
    @OnOpen
    public void onOpen(@PathParam("carId") String carId, @PathParam("timestamp") int timestamp, Session session) {
        log.info("Video: WebSocketV2Manager new session：{}, car:{}", session.getId(), carId);
        Object o = session.getUserProperties().get("User-Agent");
        if (Objects.nonNull(o)) {
            List<String> userAgents = (List<String>) o;
            if (!CollectionUtils.isEmpty(userAgents)) {
                for (String userAgent : userAgents) {
                    if (MobileChecker.isMobile(userAgent)) {
                        throw new UnAuthorizedException("未授权");
                    }
                }
            }
        }

        synchronized (sessions) {
            playVideo(carId, timestamp, session);
        }
    }

    private void playVideo(String carId, int timestamp, Session session) {
        log.info("Video: replayVideo");
        // timestamp == 0 为直播情况
        if (timestamp == 0) {
            // 实时播放的时候是根据carId来存session
            sessions.computeIfAbsent(carId, k -> new ArrayList<>()).add(session);
            videoService.liveVideo(carId, session.getId());
        } else {
            //同一个carId可能建立多个session
            sessions.computeIfAbsent(carId + "-" + timestamp + "-" + session.getId(), k -> new ArrayList<>()).add(session);
            ReplayVideoRequestDTO replayVideoRequestDTO = new ReplayVideoRequestDTO();
            String format = sdf.format(new Timestamp(timestamp * 1000L));
            replayVideoRequestDTO.setTimestamp(timestamp);
            replayVideoRequestDTO.setDate(format);
            videoService.replayVideo(carId, carId + "-" + timestamp + "-" + session.getId(), replayVideoRequestDTO);
        }
    }


    @Override
    public void increaseSession(String carId, String sessionId) {
        log.info("WebSocketV2Manager increaseSession");
//        videoService.liveVideo(carId, sessionId);
    }

    @Override
    public void decreaseSession(String key, String sessionId) {
        String[] split = key.split("-");
        if (split.length == 3 && "0".equals(split[1])) {
            videoService.stopLiveVideo(split[0], sessionId);
        } else {
            videoService.stopReplayVideo(key);
        }
    }


}